﻿Imports GMap.NET
Imports System.Net
Imports System.Web
Imports System.IO
Imports System.Xml.Linq
Imports System.Globalization


Public Class GeocoderLocationService

    Public Sub New()

    End Sub

    Public Function Locate(ByVal address As String) As PointLatLng

        address = address.Replace(Environment.NewLine, " ")

        Dim webRequest As WebRequest = webRequest.Create(
            "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=" & HttpUtility.UrlEncode(address))

        Using webResponse As WebResponse = webRequest.GetResponse()
            Using responseStream As Stream = webResponse.GetResponseStream()

                Dim xDocument As XDocument = xDocument.Load(New StreamReader(responseStream))
                Dim latitudeElement As XElement = xDocument.Descendants("lat").FirstOrDefault()
                Dim longitudeElement As XElement = xDocument.Descendants("lng").FirstOrDefault()

                If Not IsNothing(latitudeElement) AndAlso Not IsNothing(longitudeElement) Then
                    Return New PointLatLng(Double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture),
                                           Double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture))
                End If
            End Using
        End Using
        Return Nothing
    End Function



End Class
